<template>
  <div>
    <el-form :model="formData" :rules="formRules" inline ref="formData" label-position="top" class="row-form">
      <el-card class="box-card">
        <div class="card-view">
          <div class="card-title">基础信息</div>

          <el-form-item label="企业名称" prop="name" class="form-item-css">
            <el-input v-model="formData.name" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="统一社会信用代码" prop="creditCode" class="form-item-css">
            <el-input v-model="formData.creditCode" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="法定代表人姓名" prop="legalPerson" class="form-item-css">
            <el-input v-model="formData.legalPerson" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="法定代表人联系电话" prop="phone" class="form-item-css">
            <el-input v-model="formData.phone" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="运营人姓名" prop="operateName" class="form-item-css">
            <el-input v-model="formData.operateName" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="运营人联系方式" prop="operatePhone" class="form-item-css">
            <el-input v-model="formData.operatePhone" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="封面图" prop="indexImage" class="form-item-css">
            <div class="image-view" v-if="formData.indexImage">
              <el-image :src="formData.indexImage" fit="cover" style="width: 100%; height: 100%"></el-image>
              <i class="el-icon-circle-close" @click="formData.indexImage = null"></i>
            </div>
            <UploadFile v-model="formData.indexImage" v-else style="width: 100%"/>
          </el-form-item>

          <el-form-item label="营业执照" prop="licenseImage" class="form-item-css">
            <div class="image-view" v-if="formData.licenseImage">
              <el-image :src="formData.licenseImage" fit="cover" style="width: 100%; height: 100%"></el-image>
              <i class="el-icon-circle-close" @click="formData.licenseImage = null"></i>
            </div>
            <UploadFile v-model="formData.licenseImage" v-else style="width: 100%"/>
          </el-form-item>

          <el-form-item label="法人身份证人像面" prop="cardPhotoJust" class="form-item-css">
            <div class="image-view" v-if="formData.cardPhotoJust">
              <el-image :src="formData.cardPhotoJust" fit="cover" style="width: 100%; height: 100%"></el-image>
              <i class="el-icon-circle-close" @click="formData.cardPhotoJust = null"></i>
            </div>
            <UploadFile v-model="formData.cardPhotoJust" v-else style="width: 100%"/>
          </el-form-item>

          <el-form-item label="法人身份证国徽面" prop="cardPhotoBack" class="form-item-css">
            <div class="image-view" v-if="formData.cardPhotoBack">
              <el-image :src="formData.cardPhotoBack" fit="cover" style="width: 100%; height: 100%"></el-image>
              <i class="el-icon-circle-close" @click="formData.cardPhotoBack = null"></i>
            </div>
            <UploadFile v-model="formData.cardPhotoBack" v-else style="width: 100%"/>
          </el-form-item>
        </div>


      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="row-between card-title">
            <div>关联主账号</div>
            <el-button type="text" @click="formData.userRoleList.push({ wxUserId: null, roleType: 4 })">新 增</el-button>
          </div>
          <!--:rules="[{ required: true, message: '请选择账号UID', trigger: 'change' }]"-->
          <el-form-item :label="items.roleType == 3 ? '主账号UID' : '账号UID'" :prop="`userRoleList[${index}].wxUserId`"
                        v-for="(items,index) in formData.userRoleList" :key="index" class="form-item-css"
                        >
            <div v-if="items.roleType == 3 && !(!detailId)">
              <el-button type="warning" class="delete-but" style="color: white" v-if="alterUserId"
                         @click="alterUserId = false">更 换
              </el-button>
              <div v-else-if="!alterUserId">
                <el-button class="delete-but" style="color: #333;" @click="alterUserId = true">
                  取 消
                </el-button>
              </div>
            </div>
            <div v-else-if="items.roleType != 3">
              <el-button type="text" class="delete-but" @click="userRoleDelete(items,index)">删 除</el-button>
            </div>
            <el-select v-model="items.wxUserId" filterable placeholder="请选择"
                       @change="onEditUserIdEvent($event, items)" style="width: 100%;"
                       :disabled="items.roleType == 3 ? !(!detailId) && alterUserId : !(!items.id)">
              <el-option v-for="(item, index) in userList" :key="index" :label="item.nickName" :value="item.id"
                         :disabled="formData.userRoleList.some(it => item.id == it.wxUserId)">
                <span style="float: left">{{ item.nickName }}</span>
                <span style="float: right;">
                   <el-image :src="item.headimgUrl" fit="cover" style="width: 32px; height: 32px;"></el-image>
                </span>
              </el-option>
            </el-select>

          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="row-between card-title">
            <div>关联园区</div>
          </div>

          <el-form-item label="园区名称" prop="gardenId" class="form-item-css">
            <el-select v-model="formData.gardenId" style="width: 100%" placeholder="请选择" filterable remote reserve-keyword :remote-method="remoteMethod">
              <el-option :label="item.gardenName" :value="item.id" v-for="(item, index) in gardenList" :key="index"/>
            </el-select>
          </el-form-item>
        </div>

      </el-card>

      <div class="row-div" style="margin: 30px 0">
        <el-button style="width: 300px">取 消</el-button>
        <el-button type="primary" style="width: 300px" @click="detailId ? onEditEvent() : onSubmit()">提 交</el-button>
      </div>

    </el-form>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    computed: {
      ...mapGetters(['confirm'])
    },
    name: 'enterpriseAdd',
    async beforeMount() {
      await this.getUserList()
      
      if (this.$route.query.detailId) {
        this.detailId = this.$route.query.detailId || null
        await this.getDetailRequest()
        await this.getUidRoleList()
      }
      await this.getGardenList()
    },
    data() {
      return {
        gardenList: [],
        userList: [],
        formData: {
          userRoleList: [{ wxUserId: null, roleType: 3 }],
          abbreviation: null, // 企业简称
          address: null, // 地址
          annualReportAddress: null, // 最新年报地址
          auditTime: null, // 核准日期
          cardId: null, // 身份证号码
          cardPhotoBack: null, // 身份证照片反面
          cardPhotoJust: null, // 身份证照片正面
          checkReason: null, // 状态2时的审核原因
          checkStatus: null, // 认证状态：0待审核；1审核通过；2拒绝
          city: null, // 城市
          county: null, // 区县
          createTime: null, //
          creditCode: null, // 统一社会信用代码/纳税人识别号/组织结构代码
          email: null, // 企业联系邮箱，多个邮箱用英文逗号隔开
          englishName: null, // 英文名称
          enterpriseType: null, // 企业类型：如有限公司、独资企业
          establishTime: null, // 成立日期
          gardenId: null, // 园区id
          id: null, //
          indexImage: null, // 封面图片
          industry: null, // 行业
          insuredCount: null, // 参保人数
          isQcc: null, // 企查查数据是否存在：0不存在；1存在
          legalPerson: null, // 法人代表
          licenseImage: null, // 营业执照图片
          logo: null, // 企业logo
          manageScope: null, // 经营范围
          name: null, // 企业名称
          onceName: null, // 曾用名，多个名称用英文逗号隔开
          operateName: null, // 运营人姓名
          operatePhone: null, // 运营人联系电话)
          phone: null, // : null, // 企业联系电话，多个号码用英文逗号隔开
          profile: null, // 企业简介
          province: null, // 省份
          register: null, // 企业状态：暂时字符串类型（存续、在业、注销等）
          registerCapital: null, // 注册资本
          roomNumber: null, // 所在位置(楼号.单元号.房号)
          signInCode: null, // 企业注册号（13位）
          userId: null, // 用户id：没有认领默认为0
          videoUrl: null, // 视频路径
          website: null // 网址
        },
        formRules: {
          name: [
            { required: true, message: '请输入企业名称', trigger: 'blur' }
          ],
          creditCode: [
            { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
          ],
          legalPerson: [
            { required: true, message: '请输入法定代表人姓名', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入法定代表人联系电话', trigger: 'blur' }
          ],
          operateName: [
            { required: true, message: '请输入运营人姓名', trigger: 'blur' }
          ],
          operatePhone: [
            { required: true, message: '请输入运营人联系方式', trigger: 'blur' }
          ],
          indexImage: [
            { required: true, message: '请上传封面图', trigger: 'blur' }
          ],
          licenseImage: [
            { required: true, message: '请上传营业执照', trigger: 'blur' }
          ],
          cardPhotoJust: [
            { required: true, message: '请上传法人身份证人像面', trigger: 'blur' }
          ],
          cardPhotoBack: [
            { required: true, message: '请上传法人身份证国徽面', trigger: 'blur' }
          ],
          gardenId: [
            { required: true, message: '请选择园区名称', trigger: 'blur' }
          ]
        },
        detailId: null,
        alterUserId: true,
      }
    },
    methods: {
      remoteMethod(query){
        this.getGardenList(query)
      },
      onEditEvent() {
        this.$refs.formData.validate(async(valid) => {
          if (!valid) return this.$message.warning('请完善信息')
          const formData = JSON.parse(JSON.stringify(this.formData))
          await this.$ajax.post('/enterprise/update', formData)
          this.$message.success('修改成功!')
          this.$router.push('/enterpriseManage/enterpriseList')
        })
      },
      onSubmit () {
        this.$refs.formData.validate(async(valid) => {
          if (!valid) return
          const formData = JSON.parse(JSON.stringify(this.formData))
          formData.userId = this.formData.userRoleList.shift().wxUserId
          const res = await this.$ajax.post('/enterprise/backstage/add', formData)
          const list = formData.userRoleList;
          for(let i = 0; i < list.length; i++){
            const item = list[i]
            await this.$ajax.post('/wx/role/add', { roleType: item.roleType, enterpriseId: res.data.id, wxUserId: item.wxUserId })
          }
          this.$message.success('操作成功!')
          this.$router.push('/enterpriseManage/enterpriseList')
        })
      },
      async getDetailRequest () {
        const res = await this.$ajax.get(`/enterprise/backstage/info?id=${this.detailId}`)
        res.data.userRoleList = [{ wxUserId: null, roleType: 3 }]
        delete res.data.userId
        this.formData = res.data
      },
      /**
       * 获取用户列表
       */
      async getUserList() {
        const res = await this.$ajax.get('/wx/user/phone/search')
        this.userList = res.rows
      },
      /**
       * 园区列表
       */
      async getGardenList(value) {
        // const res = await this.$ajax.get('/garden/backstage/list')
        // this.gardenList = res.rows
        if(this.formData.gardenId || value){
        value?this.formData.gardenId='':this.formData.gardenId
        const res = await this.$ajax.get(`/wx/entrust/backstage/gardenType/list?gardenId=${this.formData.gardenId?this.formData.gardenId:''}&gardenName=${value || ''}`).finally(() => this.loading = false)
        this.gardenList = res.rows
        }
      },
      /**
       * 删除账号UID
       */
      userRoleDelete (item, index) {
        if (!item.id) {
          if (this.formData.userRoleList.length <= 1) return this.$message.warning("主账号不能删除")
          return this.formData.userRoleList.splice(index, 1)
        }
        this.$confirm(this.confirm.text, '提示', this.confirm.options).then(async() => {
          await this.$ajax.get(`/wx/role/remove?id=${item.id}`)
          this.$message.success('操作成功')
          this.formData.userRoleList.splice(index, 1)
        })
      },
      /**
       * 修改主账号UID
       */
      async onEditUserIdEvent(event, user) {
        if (!this.detailId) return;
        await this.$ajax.post(user.id ? '/enterprise/backstage/role' : '/wx/role/add', {
          roleType: user.roleType,
          enterpriseId: this.detailId,
          id: user.id || null,
          wxUserId: user.wxUserId,
        })
        this.alterUserId = true
        this.$message.success('操作成功')
        await this.getDetailRequest()
        await this.getUidRoleList()
      },
      /**
       * 获取主账号Uid列表
       */
      async getUidRoleList() {
        const res = await this.$ajax.get(`/wx/role/list?enterpriseId=${this.detailId}`)
        this.formData.userRoleList = res.rows && res.rows.length ? res.rows : [{ wxUserId: null, roleType: 3 }]
      },
    }
  }
</script>

<style scoped lang="scss">
  .box-card + .box-card {
    margin-top: 20px;
  }

  .image-list {
    width: 148px;
    height: 148px;
    position: relative;
    margin-right: 10px;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    &:hover > .image-hover {
      display: flex;
      z-index: 1;
    }
    .image-item, .image-hover {
      width: 100%;
      height: 100%;
      border-radius: 6px;
    }
    .image-hover {
      position: absolute;
      top: 0;
      left: 0;
      display: none;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      font-size: 20px;
    }
  }

  .card-view {
    width: 100%;
    .card-title {
      width: 200px;
      font-weight: bold;
      font-size: 18px;
      padding-bottom: 10px;
      margin-bottom: 20px;
      position: relative;
      &:before {
        content: "";
        width: 200px;
        height: 1px;
        background: #000000;
        position: absolute;
        bottom: 0;
        left: 0;
      }
    }

    .form-item-css {
      width: calc(100% / 3 - 10px);
      position: relative;
      .delete-but {
        position: absolute;
        color: red;
        z-index: 2;
        right: 0;
        top: -40px;
      }
    }
  }

  .image-view {
    width: 100%;
    height: 178px;
    position: relative;
    .el-icon-circle-close {
      font-size: 30px;
      color: red;
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 100;
    }
    .el-icon-circle-close:hover {
      cursor: pointer;
    }
  }
</style>
